<?php

namespace App\Http\Api\Services;

use App\Exceptions\InvalidRequestException;
use App\Http\Models\Feedback;
use App\Http\Models\Order;
use App\Http\Models\Product;
use App\Http\Models\ProductSku;
use App\Http\Services\BaseService;
use http\Exception\InvalidArgumentException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class ProductService extends BaseService
{
    /*
     * 商品采集
     * */
    public function store($attributes = [])
    {
        if(empty($attributes)){
            throw new InvalidRequestException('参数错误 不能为空');
        }
        if(!is_array($attributes)){
            $attributes = json_decode($attributes,true);
        }
        $tmp_products = [];
        if(!empty($attributes)){
            //清表
            $this->clearTable('admin_products');
            foreach ($attributes as $item){
                if(!empty($item['prod_no'])){
                    //剥离出manu_no
                    $pattern = '/[A-Z]+/';
                    $tmp_manu_no = '';
                    preg_match_all($pattern,$item['prod_no'],$m);
                    if(!empty($m[0][0])){
                        $tmp_manu_no = $m[0][0];
                    }

                    $tmp_products[] = [
                        'prod_no' => $item['prod_no'],
                        'prod_name' => $item['prod_name'],
                        'manu_no' => $tmp_manu_no,
                        'prod_img' => $item['prod_img'],
                        'cost_price' => $item['cost_price'],
                        'prod_price' =>  $item['prod_price']
                    ];
                }
            }
        }
        if(!empty($tmp_products)){
            $result = Product::insert($tmp_products);
            return $result;
        }
        return false;
    }

    /*
     * 商品sku采集
     * */
    public function skuStore($attributes = [])
    {
        if(empty($attributes)){
            throw new InvalidRequestException('参数错误 不能为空');
        }
        if(!is_array($attributes)){
            $attributes = json_decode($attributes,true);
        }
        $tmp_skus = [];
        if(!empty($attributes)){
            //去重
            $attributes = collect($attributes)->unique('sku_no')->values()->all();

            //清表
            $this->clearTable('admin_product_skus');
            foreach ($attributes as $item){
                if(!empty($item['sku_no'] && !empty($item['prod_no']))){
                    $tmp_skus[] = [
                        'sku_no' => $item['sku_no'],
                        'prod_no' => $item['prod_no'],
                        'sku_color' => $item['sku_color'],
                        'sku_size' => $item['sku_size'],
                        'sku_stock' => $item['sku_stock']
                    ];
                }
            }
        }
        if(!empty($tmp_skus)){
            $result = ProductSku::insert($tmp_skus);
            return $result;
        }
        return false;
    }

    /*
     * sku库存
     * */
    public function skuStock($prod_no){
        if(!$prod_no){
            throw new InvalidRequestException('请输入商品编号');
        }

        $skus = ProductSku::where('prod_no','like','%'.$prod_no.'%')->get();

        $sku_nos = $skus->pluck('sku_no')->toArray();

        //算出当天的销量
        $raw = DB::raw('sku_no,sum(combo_num) as order_num');
        $start_time = date('Y-m-d',time()).' 00:00:00';
        $end_time = date('Y-m-d',time()).' 23:59:59';
        $result = Order::select($raw)->whereBetween('create_time',[
            $start_time,$end_time
        ])->whereIn('sku_no',$sku_nos)->groupBy('sku_no')->get()->toArray();
        foreach ($skus as &$sku){
            $collectSkus = collect($result)->where('sku_no',$sku['sku_no']);
            if(count($collectSkus)){
                $sku['order_count'] = $collectSkus->first()['order_num'];
            }else{
                $sku['order_count'] = 0;
            }
        }

        return $skus;
    }


    /*
     * 商品微信登记
     * */
    public function reg($attributes = []){

        if(empty($attributes['prod_name'])
                || empty($attributes['prod_img'])
        ){
            throw new InvalidRequestException('商品信息必传');
        }
        if(empty($attributes['prod_no'])){
            $attributes['prod_no'] = getRandomStr(8);
        }
        $prod_no = $attributes['prod_no'];
        if(is_array($attributes['prod_img'])){
            $attributes['prod_img'] = json_encode($attributes['prod_img']);
        }
        $skus = $attributes['skus'];
        if(empty($skus)){
            throw new InvalidRequestException('sku参数为空');
        }
        if(!empty($skus)){
            foreach ($skus as &$sku){
                if(empty($sku['sku_color']) && empty($sku['sku_size'])){
                    throw new InvalidRequestException('sku参数不完整');
                }
                $sku['prod_no'] = $prod_no;
                $sku['sku_no'] =  $prod_no.'_'.$sku['sku_color'].'_'.$sku['sku_size'];
            }
        }

        unset($attributes['skus']);
        if(Product::where('prod_no',$prod_no)->count()){
            Product::where('prod_no',$prod_no)->update($attributes);
            ProductSku::where('prod_no',$prod_no)->delete();
            ProductSku::insert($skus);
            return $prod_no;
        }else{
            $p = Product::create($attributes);
            $p->skus()->createMany($skus);
            return $p->prod_no;
        }
    }

    public function productItem($prod_no){
        if($prod_no){
            if(Product::where('prod_no',$prod_no)->exists()){
                $product =  Product::where('prod_no',$prod_no)->with('skus')->first();
                $colors = [];
                $sizes = [];
                if($product->skus){
                    foreach ($product->skus as $sku){
                        if(!in_array($sku->sku_color,$colors)){
                            $colors[] = $sku->sku_color;
                        }
                        if(!in_array($sku->sku_size,$sizes)){
                            $sizes[] = $sku->sku_size;
                        }
                    }
                }
                $product->colors = implode(' ',$colors);
                $product->sizes = implode(' ',$sizes);
                return $product;
            }
        }
        return null;
    }

    /*
     * 反馈登记
     * */
    public function feedback($attributes = []){
        if(empty($attributes)){
            throw new InvalidArgumentException('参数不能为空');
        }

        $result = Feedback::create($attributes);

        return $result;
    }

    /*
     * 阅读反馈消息
     * */
    public function isReadFeedback($attributes = []){
        if(empty($attributes['id'])){
            throw new InvalidArgumentException('参数不能为空');
        }
        Feedback::where('id',$attributes['id'])->update(['read'=>1]);
        return ;
    }

    /*
     * 用户反馈列表数据
     * */
    public function userFeedbackList($attributes = []){
        if(empty($attributes['openid'])){
            throw new InvalidRequestException('参数缺失【openid】');
        }

        $data   =   Feedback::where('openid',$attributes['openid'])->get()->toArray();

        foreach ($data as $key => $item){
            $item['flag']   =   false;
            if($item['read']    == 0 &&  !empty($item['answer'])){
                $item['flag']   =   true;
            }
            $data[$key] =   $item;
        }

        return $data;

    }
}
